const fs = require('fs');
const path = require('path');

function findVueFiles(dir) {
  const vueFiles = [];
  
  function traverse(currentDir) {
    const files = fs.readdirSync(currentDir);
    
    files.forEach(file => {
      const fullPath = path.join(currentDir, file);
      const stat = fs.statSync(fullPath);
      
      if (stat.isDirectory() && !file.startsWith('.')) {
        traverse(fullPath);
      } else if (file.endsWith('.vue')) {
        vueFiles.push(fullPath);
      }
    });
  }
  
  traverse(dir);
  return vueFiles;
}

function fixWeappCompatibility() {
  const srcDir = path.join(__dirname, 'src');
  const vueFiles = findVueFiles(srcDir);
  
  let fixedCount = 0;
  
  vueFiles.forEach(filePath => {
    let content = fs.readFileSync(filePath, 'utf8');
    let originalContent = content;
    
    // 修复 vh 单位
    content = content.replace(/(\d+)vh/g, (match, num) => {
      return Math.round(parseInt(num) * 13.34) + 'rpx';
    });
    
    // 修复 gap 属性（简单替换为 margin-right）
    content = content.replace(/gap:\s*(\d+)rpx/g, 'margin-right: $1rpx');
    
    // 修复 flex: 1 1 auto 语法
    content = content.replace(/flex:\s*1\s+1\s+auto/g, 'flex: 1');
    
    // 修复嵌套注释问题
    content = content.replace(/\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//g, '');
    
    if (content !== originalContent) {
      fs.writeFileSync(filePath, content, 'utf8');
      console.log(`已修复: ${path.relative(srcDir, filePath)}`);
      fixedCount++;
    }
  });
  
  console.log(`修复完成！共修复了 ${fixedCount} 个文件`);
}

// 执行修复
fixWeappCompatibility();